//
//  WKWebView+BKExt.swift
//  dysaidao
//
//  Created by 王锦发 on 2020/4/29.
//  Copyright © 2020 王锦发. All rights reserved.
//

import Foundation
import WebKit

extension WKWebView {
    
    static var wkWebConfig: WKWebViewConfiguration {
        // WKWebView自适应大小
        let jScript = "var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);"
        let wkUScript = WKUserScript(source: jScript, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
        let wkUController = WKUserContentController()
        wkUController.addUserScript(wkUScript)

        let wkWebConfig = WKWebViewConfiguration()
        wkWebConfig.preferences = WKPreferences()
        wkWebConfig.preferences.minimumFontSize = 10
        wkWebConfig.preferences.javaScriptEnabled = true
        wkWebConfig.preferences.javaScriptCanOpenWindowsAutomatically = false
        wkWebConfig.processPool = WKProcessPool()
        wkWebConfig.applicationNameForUserAgent = "TimeManager"
        wkWebConfig.userContentController = wkUController
        return wkWebConfig
    }
    
}

extension WKWebView {
    
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        return false
    }
    
    func loadWithURL(_ urlString: String) {
        guard let url = URL(string: urlString) else { return }
        var req = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 20.0)
        guard let cookies = HTTPCookieStorage.shared.cookies else { return }
        let dic = HTTPCookie.requestHeaderFields(with: cookies)
        req.allHTTPHeaderFields = dic
        self.load(req)
    }
    
    // iOS11以下通过js方法添加cookie
    func addCookies(cookies: [HTTPCookie]) {
        if #available(iOS 11.0, *) {
            
        } else {
            cookies.forEach { (cookie) in
                let jsCode = String(format: "app_setCookie('%@','%@')", cookie.name, cookie.value)
                self.evaluateJavaScript(jsCode, completionHandler: nil)
            }
        }
    }
    
    // iOS11以下获取处理cookies的js
    static func getCookiesUserScript() -> WKUserScript? {
        if #available(iOS 11.0, *) {
            return nil
        } else {
            guard let path = Bundle.main.path(forResource: "MMWKCookie", ofType: "js") else { return nil }
            do {
                let jsCode = try String(contentsOfFile: path, encoding: .utf8)
                let cookieInScript = WKUserScript(source: jsCode, injectionTime: .atDocumentStart, forMainFrameOnly: false)
                return cookieInScript
            } catch _ { }
            return nil
        }
    }
    
}
